import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Divider,  message, Form, Modal} from 'antd';
import React, { useState, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { getGoodsStockReportList, delGift } from './service';
import { connect } from 'dva';
import { history } from 'umi';
import CreateForm from './components/CreateForm';
import StockForm from './components/StockForm';
import { HasPermission } from '@/components/AuthComponent/HasPermission';

const AuthButton = HasPermission(Button);
const GiftReport = props => {
  const [formValues, setFormValues] = useState({
    venueId: '',
  });
  const [createModalVisible, handleModalVisible] = useState(false);
  const [stockModalVisible, handleStockModalVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState(null);
  const [columns, setColumns] = useState([
    {
      title: '赠品名称',
      dataIndex: 'name',
      render:(text,record)=><a onClick={()=>history.push(`/stock/report/${record.id}/${record.name}`)}>{text}</a>
    },
    // {
    //   title: '场馆',
    //   dataIndex: 'venueName',
    //   hideInSearch: true,
    // },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      valueEnum: {
        0: {
          text: '草稿中',
          status: 'Warning',
        },
        1: {
          text: '使用中',
          status: 'Success',
        },
      },
    },
    {
      title: '剩余数量',
      dataIndex: 'sumQuantity',
      hideInSearch: true
    },
    {
      title: '备注',
      dataIndex: 'depict',
      hideInSearch: true
    },
    {
      title: '操作',
      dataIndex: 'oper',
      hideInSearch: true,
      render: (text, record) => {
        return (
          <>
            <a onClick={()=>handleUpdate(record)}>编辑</a>
            <Divider type="vertical" />
            <a onClick={()=>handleStock(record)}>出入库</a>
            <Divider type="vertical" />
            <a onClick={() => handleRemove(record)}>删除</a>
          </>
        )
      }
    },
  ]);
  const [form] = Form.useForm();
  const actionRef = useRef();

  const handleStock = (record) =>{
    handleStockModalVisible(true);
    setCurrentRecord(record)
  }
  /**
   * 更新节点
   * @param fields
   */
  const handleUpdate = async record => {
    handleModalVisible(true);
    setCurrentRecord(record);

  };
  /**
   *  删除节点
   * @param selectedRows
   */

  const handleRemove = async (record) => {
    Modal.confirm({
      title: '确认删除',
      icon: <ExclamationCircleOutlined />,
      okText: '确认',
      cancelText: '取消',
      onOk:async()=>{
        message.loading('正在删除');
        try {
          await delGift({
            id: record.id,
          });
          refresh();
          message.success('删除成功，即将刷新');
        } catch (error) {
          message.error('删除失败，请重试');
        }
      }
    });
  };
  const refresh = () => {
    actionRef?.current?.reload();
  }
  return (
    <PageHeaderWrapper>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        params={{
        }}
        toolBarRender={(action, { selectedRows }) => [
          <AuthButton auth={[`stock:giveaway:add`]} type="primary" onClick={() => {
            handleModalVisible(true);
            setCurrentRecord(null)
          }}>
            <PlusOutlined /> 新增
          </AuthButton>
        ]}
        tableAlertRender={({ selectedRowKeys, selectedRows }) => (
          <div>
            已选择{' '}
            <a
              style={{
                fontWeight: 600,
              }}
            >
              {selectedRowKeys.length}
            </a>{' '}
            项
          </div>
        )}
        request={params => {
          let _params = {
            pageNum: params.current,
            venueId: formValues.venueId,
            ...params,
          }
          delete _params.current
          return getGoodsStockReportList(_params)
        }}
        beforeSearchSubmit={params => {
          let _params = {
            venueId: params.venueId || formValues.venueId,
            ...params,
          }
          setFormValues(_params);
          return _params
        }}
        postData={result => result.list}
        columns={columns}
        rowSelection={{}}
      />
      <CreateForm onCancel={() => {
        handleModalVisible(false)
        setCurrentRecord(null);
      }} refresh={refresh} modalVisible={createModalVisible} currentRecord={currentRecord}>
      </CreateForm>
      <StockForm onCancel={() => {
        handleStockModalVisible(false)
        setCurrentRecord(null);
      }} refresh={refresh} modalVisible={stockModalVisible} currentRecord={currentRecord}>
      </StockForm>
    </PageHeaderWrapper>
  );
};

export default connect(({ loading, cubeGift }) => ({
  shopList: cubeGift.shopList
}))(GiftReport);